<template>
  <el-row style="height:100%">
    <page @buttons="configPermissions">
      <pageheader :event="'userPopUp'" :isShow="buttonPermissions.isAdd">
        用户信息管理
      </pageheader>
      <div class="page-content">
        <el-card class="box-card">
          <el-row style="margin-bottom: 20px">
            <Cascader
              :value.sync="company_id_arr"
              :options.sync="options"
              :width="'300px'"
              :changeEvent="'userChange'"
            >所属企业：
            </Cascader>
            <SearchInput
              style="margin-left: 20px"
              @usersearch="usersearch"
              :searchEvent="'usersearch'"
              :value="keywords"
              :searchText="'请输入关键字'"
              ref="clearText"
            >搜索：
            </SearchInput>
          </el-row>
          <el-table :data="dataTable" size="small" stripe>
            <el-table-column label="序号" type="index" :index="indexMethod" align="center" width="60"></el-table-column>
            <el-table-column label="用户名称" prop="user_name" align="center" sortable></el-table-column>
            <el-table-column label="创建时间" prop="created_time" align="center" sortable></el-table-column>
            <el-table-column label="是否禁用" prop="case_desc" align="center" v-if="buttonPermissions.isLock">
              <template slot-scope="scope">
                <el-tag :type="scope.row.is_lock == 0?'success':'warning' " >{{scope.row.is_lock == 0?'已启用':'已禁用'}}</el-tag>
              </template>
            </el-table-column>
            <el-table-column v-if="buttonPermissions.isModify || buttonPermissions.isWatch || buttonPermissions.isDel"
                             label="操作" align="center" width="350">
              <template slot-scope="scope">
                <el-button v-if="buttonPermissions.isModify || buttonPermissions.isWatch" @click="userData(scope.row)" size="small">详情</el-button>
                <el-button  v-if="scope.row.is_lock == 0 && buttonPermissions.isLock" @click="disableUser(scope.row,0)"  type="warning" size="small">禁用</el-button>
                <el-button v-else-if="scope.row.is_lock == 1 && buttonPermissions.isLock" @click="disableUser(scope.row,1)" type="success" size="small">启用</el-button>
                <el-button v-if="buttonPermissions.isReset" @click="userReset(scope.row)" type="primary" size="small">重置密码</el-button>
                <el-button v-if="buttonPermissions.isDel" @click="userDel(scope.row)" type="danger" size="small">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination background
                         layout="total,sizes,prev,pager,next"
                         @current-change="currentChange"
                         @size-change="sizeChange"
                         :page-sizes="pagination.pageSizes"
                         :page-size.sync="pagination.pageSize"
                         :total="pagination.total"
                         :current-page.sync="pagination.currentPage"
                         class="paging fr">
          </el-pagination>
        </el-card>
        <!--新增模态框-->
        <el-dialog v-dialogDrag :title="pageTitle" :visible.sync="isShow" width="800px" top="10vh" @opened="openDialog" @close="closeDialog('ruleForm')"
                   :modal-append-to-body="false" :close-on-click-modal="false">
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="180px">
            <el-form-item label="所属企业" prop="company_id_arr">
              <Cascader :value.sync="ruleForm.company_id_arr"
                        :options="options"
                        :changeEvent="'companyChange'"
                        :width="'500px'"
                        :disabled="isDisabled"
                        :isClearable="false"></Cascader>
            </el-form-item>
            <el-form-item label="用户名" prop="user_name">
              <el-input v-model.trim="ruleForm.user_name" :disabled="isDisabled" maxlength="30" size="small" style="width:500px"></el-input>
            </el-form-item>
            <el-form-item v-if="!isDisabled" label="输入密码" prop="user_pwd">
              <el-input v-model="ruleForm.user_pwd" size="small" show-password style="width:500px" maxlength="20"></el-input>
            </el-form-item>
            <el-form-item v-if="!isDisabled" label="再次输入密码" prop="user_pwd_again">
              <el-input v-model="ruleForm.user_pwd_again" size="small" show-password style="width:500px" maxlength="20"></el-input>
            </el-form-item>
            <el-form-item label="菜单权限" prop="role_id_name">
              <el-input v-model="ruleForm.role_id_name" readonly="" style="width:500px;" size="small">
                <el-button v-if="ruleForm.company_id_arr" slot="append" @click="openRole">修改</el-button>
              </el-input>
              <div v-if="ruleForm.company_id_arr" @click="openRole" class="onClickDiv"></div>
            </el-form-item>
            <el-form-item label="数据权限" prop="org_auth_id_name">
              <el-input v-model="ruleForm.org_auth_id_name" readonly="" style="width:500px;" size="small">
                <el-button v-if="ruleForm.company_id_arr" slot="append" @click="openOrg">修改</el-button>
              </el-input>
              <div v-if="ruleForm.company_id_arr" @click="openOrg" class="onClickDiv"></div>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="isShow = false" size="small">取 消</el-button>
            <el-button v-if="buttonPermissions.isModify"
              type="primary" @click="confirmDialog('ruleForm')" size="small">保 存</el-button>
          </div>

          <!--菜单权限穿梭框-->
          <el-dialog v-dialogDrag title="菜单权限"
                     :visible.sync="showRoleTransfer"
                     width="auto" top="20vh" class="roledialog"
                     append-to-body style="text-align: center"
                     :modal="false" @close="menuClose">
            <Transfer :value.sync="ls_role_id_list"
                      :options="transferRoleData"
                      :event="'transferRoleChange'"
                      @transferRoleChange="transferRoleChange"
                      v-if="menuRoleisShow"
            ></Transfer>
            <div slot="footer" class="dialog-footer">
              <el-button @click="showRoleTransfer = false" size="small">取 消</el-button>
              <el-button type="primary" @click="confirmRoleTransfer" size="small">保 存</el-button>
            </div>
          </el-dialog>

          <!--数据权限穿梭框-->
          <el-dialog v-dialogDrag title="数据权限" @close="orgClose" :visible.sync="showOrgTransfer" width="auto" top="15vh" class="roledialog orgdialog" append-to-body :close-on-press-escape="false" :close-on-click-modal="false"  :modal="false">
            <el-row style="border-bottom:1px solid #dcdcdc;">
              <h3><span>当前选择用户：</span>{{orgHeadText.name}}</h3>
              <h3><span>所属企业：</span>{{orgHeadText.companyName}}</h3>
            </el-row>
            <div style="margin-top:15px;"></div>
            <el-col :span="11">
                <div class="clear">
                  <h3 style="margin:5px 0 15px;float:left;">已选数据权限</h3>
                </div>
                <el-table stripe  border :data="submitOrgData"   style="width: 100%" 
                size="small" :header-cell-style="{background:'rgb(248,245,254)'}"
                  height="350">
                  <el-table-column prop="company_name" align="center" label="所属企业" ></el-table-column>
                  <el-table-column prop="org_auth_name" align="center" label="权限名称" ></el-table-column>
                  <el-table-column label="权限等级" prop="org_type" align="center" >
                    <template slot-scope="scope">
                      <el-tag :type="scope.row.org_type == 1?'success':(scope.row.org_type == 2?'':'info') " >{{scope.row.org_type == 1?'企业':(scope.row.org_type == 2?'案场':'区域')}}</el-tag>
                    </template>
                  </el-table-column>
                   <el-table-column label="操作" align="center" width="100px">
                  <template slot-scope="scope">
                    <el-button type="text" style="padding: 0;" @click="delOrg(scope.row)">
                      删除
                    </el-button>
                  </template>
                </el-table-column>
                </el-table>
            </el-col>
            <el-col :span="11" :offset="1">
                <div class="clear">
                  <h3 style="margin:5px 0 15px;float:left;">待选数据权限</h3>
                  <div class="areasearch-Box" >
                     <SearchInput
                        style="margin-left: 20px;float:left;"
                        @orgSearch="orgSearch"
                        :searchEvent="'orgSearch'"
                        :value="orgkeywords"
                        :searchText="'请输入权限名称'"
                        ref="clearText"
                      >搜索：
                     </SearchInput>
                  </div>
                </div>
                <el-table stripe  border :data="orgData" v-loading.lock="orgdxLoading" ref="orgDataTable"   style="width: 100%" 
                size="small" @select="checkOrgRow" @select-all="checkoRgAll" :header-cell-style="{background:'rgb(248,245,254)'}"
                  height="350">
                  <el-table-column type="selection" prop="id" align="center"   width="50"></el-table-column>
                  <el-table-column prop="company_name" align="center" label="所属企业" ></el-table-column>
                  <el-table-column prop="org_auth_name" align="center" label="权限名称" ></el-table-column>
                  <el-table-column label="权限等级" prop="org_type" align="center" >
                    <template slot-scope="scope">
                      <el-tag :type="scope.row.org_type == 1?'success':(scope.row.org_type == 2?'':'info') " >{{scope.row.org_type == 1?'企业':(scope.row.org_type == 2?'案场':'区域')}}</el-tag>
                    </template>
                  </el-table-column>
                </el-table>
                <el-pagination background
                         layout="total,sizes,prev,pager,next"
                         @current-change="orgCurrentChange"
                         @size-change="orgSizeChange"
                         :page-sizes="orgPagination.pageSizes"
                         :page-size.sync="orgPagination.pageSize"
                         :total="orgPagination.total"
                         :current-page.sync="orgPagination.currentPage"
                         class="paging fr">
                </el-pagination>
            </el-col>            
            <!-- <Transfer :value.sync="ruleForm.org_list"
                      :options="orgData"
                      :event="'transferOrgChange'"
                      @transferOrgChange="transferOrgChange"
            ></Transfer> -->
            <div slot="footer" class="dialog-footer">
              <el-button @click="showOrgTransfer = false" size="small">取 消</el-button>
              <el-button type="primary" @click="confirmOrgTransfer" size="small">保 存</el-button>
            </div>
          </el-dialog>
        </el-dialog>
        <!--重置密码模态框-->
        <el-dialog
          title="重置密码"
          :visible.sync="passwordReset"
          class="indivdialog changepwd"
          v-dialogDrag
          @close="reForm"
          width="40%"
          top='12vh'
          center>
          <el-form :model="FormVal" status-icon :rules="resetFormRules" ref="FormVal" label-width="80px">
            <el-form-item label="新密码" prop="newpwd">
              <el-input type="password" v-model="FormVal.newpwd" auto-complete="off" show-password></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="renewpwd">
              <el-input type="password" v-model="FormVal.renewpwd" auto-complete="off" show-password></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button size="small" @click="passwordReset=false">取 消</el-button>
            <el-button size="small" type="primary" @click="submitForm('FormVal')">提 交</el-button>
          </div>
        </el-dialog>
      </div>
    </page>
  </el-row>
</template>
<style lang="scss">
.page-content {
  padding: 15px;
  .fr {
    float: right;
  }
  .el-table {
    margin-bottom: 10px;
  }
  .paging {
    margin: 15px;
    height: 28px;
  }
}
.onClickDiv{
  display: inline-block;
  width: 70%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  cursor: pointer;
}
.roledialog{
  .el-dialog{
    max-width: 1300px;
    .el-transfer-panel{
      width:395px;
    }
  }
}
.orgdialog{
  .el-dialog{
    .el-dialog__body{
      .el-row{
        h3{
          display:inline-block;
          font-size: 17px;
          span{
            color: #bbb;
          }
          &:last-child{
            margin-left: 20px;
          }
        }
        padding-bottom:20px;
      }
      &::after,&::before{
        content:'';
        display:block;
        clear:both;
      }
    }
  }
}
.areasearch-Box{
    float: right;
    line-height: 30px;
    height: 30px;
  }
</style>
<script>
import page from "@/components/page/page";
import pageheader from "@/components/page/pageheader";
import SearchInput from "@/components/sys/assembly/searchinput";
import Transfer from "@/components/sys/assembly/transfer";
import Cascader from "@/components/sys/assembly/elcascader";
import Moment from "moment";

export default {
  data() {
    let validatePass = (rule, value, callback) => {
      if (value === '') {
        return  callback(new Error('请输入密码'));
      } else {
        let str = /^[a-zA-Z0-9_]+$/
        if(!str.test(value)){
          return callback(new Error('密码只能输入大小写英文，数字和下滑线'));
        }
        if (this.ruleForm.user_pwd_again !== '') {
          this.$refs.ruleForm.validateField('user_pwd_again');
        }
        callback();
      }
    };
    let validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.ruleForm.user_pwd) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        let str = /^[a-zA-Z0-9_]+$/
        if(!str.test(value)){
          return callback(new Error('密码只能输入大小写英文，数字和下滑线'));
        }
        callback();
      }
    };
    //案场编码表单校验，判断案场编码是否存在
    let validateUserName = (rule, value, callback)=>{
      if(this.isDisabled) return callback()
      if (!value) {
        return callback(new Error('用户名不能为空'));
      }else{
        let str = /^[a-z][a-z0-9_]+$/
        if(!str.test(value)){
          return callback(new Error('用户名只能输入小写英文，数字和下滑线,且第一位必须为字母'));
        }
      }
      let url = '/sys/user/exist_username?user_name='+ value;
      this.$api.post(url)
      .then(data =>{
        if(data == '10001'){
          this.$message.error('无权操作该数据')
          this.$Bus.$emit('Loading',false);
        }
        if(data.data){
          callback(new Error('用户名已使用'));
        }else{
          callback();
        }
      })
    }

    //修改密码表单验证
    let resetPass = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入新密码'));
      } else if (value.toString().length < 6 || value.toString().length > 18) {
        callback(new Error('密码长度为6 - 18个字符'))
      } else{
        callback();
      }
    };
    let resetPass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.FormVal.newpwd) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      loading: true,
      pageTitle: "用户管理信息",
      isShow: false,//是否显示模态框
      isDisabled:false,//是否是修改状态
      menuRoleisShow:false, //菜单权限穿梭框显示隐藏
      dataTable:[],//表格数据
      options:[],//级联控件 所属上级菜单
      company_id_arr:[],//所属企业id arr
      company_id:[],//所属企业id
      keywords:'',
      orgkeywords:'',   //数据权限关键词搜索
      ruleForm: {
        id:'',//用户id
        company_id:'',//所属企业id
        company_id_arr:'',//所属企业id arr
        user_name:'',//用户名
        user_pwd:'',//密码
        user_pwd_again:'',//再次输入密码
        org_list:[],//已选数据权限 list
        org_auth_id_name:'',//数据权限 ID名称
        role_id_list:[],//控制权限 ID list
        role_id_name:'',//控制权限ID名称
      },
      ls_role_id_list:[],
      rules: {
        user_name:[
          { required: true, validator:validateUserName, trigger: "blur"},
        ],
        user_pwd: [
          { required: true, validator:validatePass, trigger: "blur"},
          { min: 6, max: 20, message: "密码长度在 6 到 20 个字符", trigger: "blur"}
        ],
        user_pwd_again: [
          { required: true, validator:validatePass2, trigger: "blur"},
          { min: 6, max: 20, message: "密码长度在 6 到 20 个字符", trigger: "blur"}
        ],
        company_id_arr: [{ required: true, message: "请选择所属企业",trigger:'change'}],
      },
      transferRoleData:[],//控制权限穿梭框list
      showRoleTransfer:false,//是否显示控制权限穿梭框模态框
      orgData:[],//数据权限表格list
      orgHeadText:{   //数据权限头部信息
        name:'',
        companyName:'',
      },
      tableCheckOrg:[], //表格每次勾选的lsit
      submitOrgData:[], //已选数据全选表格数据
      orgdxLoading:false, //待选表格loading
      showOrgTransfer:false,//是否显示数据权限穿梭框模态框
      buttonPermissions:{
        isAdd:false,
        isDel:false,
        isModify:false,
        isWatch:false,
        isLock:false,
        isReset:false,
      },
      columns:[
        {
          text: "用户名称",
          value: "user_name",
          align: "center",
        },
        {
          text:"创建时间",
          value:"created_time",
          align:"center"
        },
      ],
      pagination:{
        total:0,//总条目数
        currentPage:1,//当前页数
        pageSize:10,//每页显示条目个数
        pageSizes:[10,20,50,100],//每页显示个数选择器的选项设置
      },//表格分页参数
      orgPagination:{
        total:0,//总条目数
        currentPage:1,//当前页数
        pageSize:10,//每页显示条目个数
        pageSizes:[10,20,50,100],//每页显示个数选择器的选项设置
      },//数据权限分页参数
      isorgdyc:true,  //数据权限是否第一次打开(判断是否需要给左侧表格赋值)
      passwordReset:false,//是否显示重置密码模态框
      FormVal: {
        newpwd: '',
        renewpwd: '',
      },
      resetFormRules: {
        newpwd: [
          { required: true, validator: resetPass, trigger: 'blur' }
        ],
        renewpwd: [
          { required: true, validator: resetPass2, trigger: 'blur' }
        ],
      },
      userId:'',//选中用户id
      isRoot:false,//是否是root
    };
  },
  inject: ["reload"],
  components: {
    page,
    pageheader,
    Cascader,
    SearchInput,
    Transfer
  },
  watch: {
    // OrgSearch(val,oldval){
    //   this.tableCheckOrg=[];
    //   this.$nextTick(()=>{
    //     if (this.submitOrgData && this.submitOrgData.length > 0) {
    //       this.submitOrgData.forEach((ms,msIndex) => {
    //         for (let i = 0; i < this.orgData.length; i++) {
    //           const el = this.orgData[i];
    //           if(ms.id==el.id){
    //             this.tableCheckOrg.push(el);
    //             this.$refs.orgDataTable.toggleRowSelection(el, true);
    //           }
    //         }
    //       })
    //     }   
    //   })
    // }
  },
  created() {
    this.getTree()
    //判断是否有按钮权限
    if (sessionStorage.buttonPermissions) {
      this.configPermissions(JSON.parse(sessionStorage.buttonPermissions))
    }
    this.isRoot = localStorage.isRoot == 1 ? true :false;
  },
  computed:{
    // OrgTables:function(){
    //   let search = this.OrgSearch;
    //     if (search) {
    //       return this.orgData.filter(function (dataNews) {
    //         return Object.keys(dataNews).some(function (key) {
    //           return String(dataNews[key]).toLowerCase().indexOf(search) > -1
    //         })
    //       })
    //     };
        
    //     return this.orgData;
    // }
  },
  mounted(){
    this.$Bus.$on('userPopUp', () => {
      this.isShow = true;
      this.isDisabled = false;
    })
    this.$Bus.$on('userChange', data => {
      console.log(data);
      this.company_id_arr = data
      this.$Bus.$emit('Loading', true)
      this.company_id = data.slice(-1)[0]
      this.keywords = ''
      this.getUserList(this.company_id)
    })
    this.$Bus.$on('companyChange', data => {
      this.ruleForm.company_id_arr = data
      this.ruleForm.company_id = data.slice(-1)[0]
      this.ruleForm.org_list = []
      this.ruleForm.role_id_list = []
      this.ruleForm.org_auth_id_name = ''
      this.ruleForm.role_id_name = ''
      this.$refs.ruleForm.validateField('company_id_arr');//触发form表单中校验所属企业是否选择
    })
  },
  beforeDestroy(){
    //销毁Bus绑定事件
    this.$Bus.$off("userPopUp");
    this.$Bus.$off("userChange");
    this.$Bus.$off("companyChange");
  },
  methods: {
    //配置按钮权限，根据权限不同调整表头渲染参数
    configPermissions(val){
      let buttonPermissions = val
      let menuButtonPermissions = [];//按钮权限数组
      buttonPermissions.forEach(e =>{
        for(let key in e){
          if(key == 'menu_code'){
            menuButtonPermissions.push(e[key])
          }
        }
      });
      this.buttonPermissions.isAdd = menuButtonPermissions.includes('userAdd') ? true : false; //是否有新增权限
      this.buttonPermissions.isReset = menuButtonPermissions.includes('userReset') ? true : false; //是否有重置密码权限
      this.buttonPermissions.isModify = menuButtonPermissions.includes('userModify') ? true : false; //是否有修改权限
      this.buttonPermissions.isWatch = menuButtonPermissions.includes('userWatch') ? true : false; //是否有查看权限
      this.buttonPermissions.isLock = menuButtonPermissions.includes('userLock') ? true : false; //是否有禁用权限
      this.buttonPermissions.isDel = menuButtonPermissions.includes('userDelete') ? true : false; //是否有删除权限

    },
    //获取企业tree
    getTree(){
      let url = '/sys/report_assist_new/company_tree';
      this.$api.get(url)
      .then(data => {
        // console.log(data,'data');
        if(data == '10001'){
          this.$message.error('无权操作该数据')
          this.$Bus.$emit('Loading',false);
          return
        }
        if(data){
          recursion(data.data);
          function recursion(val) {
            if(val.length){
              for(let i in val){
                val[i].value = val[i].id;
                val[i].label = val[i].company_name;
                val[i].parent_id_str = val[i].parent_name_list.join('/');
                if(val[i].children && val[i].children.length){
                  recursion(val[i].children)
                }else{
                  delete val[i].children
                }
              }
            }
          }
          this.options = data.data
          this.company_id = data.data[0].id
          this.company_id_arr.push(data.data[0].id)

          this.getUserList(this.company_id)
        }
        this.$Bus.$emit('Loading',false)
      })
      .catch(err=>{
         console.log(err);
        this.$Bus.$emit('Loading',false)
      })
    },
    getUserList(company_id = '',keywords = '',page = 1,page_size = 10){
      let url = '/sys/user/get-user-list?company_id='+ company_id + '&keywords='+ encodeURIComponent(keywords) +
      '&page='+ page + '&page_size=' + page_size;
      this.$api.get(url)
      .then(data => {
        if(data == '10001'){
          this.$message.error('无权操作该数据')
          this.$Bus.$emit('Loading',false);
          return
        }
        // console.log(data);
        if(data){
          let _data = data.data
          for(let i in _data.dataList){
            _data.dataList[i].created_time = Moment(_data.dataList[i].created_time).format("YYYY-MM-DD HH:mm:ss")
          }
          this.dataTable = _data.dataList ? _data.dataList : [];
          this.pagination.total = _data.dataCount;
          this.pagination.currentPage = _data.pageCode;
          this.pagination.pageSize = _data.pageSize;
        }
        this.$Bus.$emit('Loading',false)
      })
      .catch(err=>{
         console.log(err);
        this.dataTable = []
        this.$Bus.$emit('Loading',false)
      })
    },
    //打开模态框
    openDialog(){
      if(!this.isDisabled){
        this.ruleForm.company_id = this.company_id_arr.slice(-1)[0];
        this.ruleForm.company_id_arr = this.company_id_arr;
      }
    },
    //关闭模态框
    closeDialog(formName){
      this.$refs[formName].resetFields();
      this.ruleForm.id = '';
      this.ruleForm.company_id_arr = null;
      this.orgPagination={
        total:0,
        currentPage:1,
        pageSize:10,
        pageSizes:[10,20,50,100],
      };
      this.orgkeywords='';
      this.submitOrgData=[];
      this.orgdxLoading=false;
      this.$set(this.ruleForm,'org_list',[])//清空标签id列表
      this.$set(this.ruleForm,'role_id_list',[])//清空标签id列表
      this.$Bus.$emit('Loading',false)
    },
    //模态框保存按钮
    confirmDialog(formName){
      let data = {};
      let model = null;
      let url = ''
      this.$refs[formName].validate(valid => {
        if (valid) {
          if(!this.ruleForm.org_list.length){
            this.$message.error('请选择数据权限')
            return
          }
          if(!this.ruleForm.role_id_list.length){
            this.$message.error('请选择菜单权限')
            return
          }
          this.$Bus.$emit('Loading',true)
          model = this.$refs[formName].model;
          model.company_id = model.company_id_arr.length !== 0 ? model.company_id_arr.slice(-1)[0] : '';
          if (this.isDisabled) {
            data.company_id  = model.company_id;
            data.org_auth_id_list  = this.ruleForm.org_list.map(x=>{
              return x.id;
            })
            data.role_id_list  = this.ruleForm.role_id_list;
            data.user_id  = this.ruleForm.id;
            url = "sys/user/update";
            // console.log(data,'data');
            this.modifyMenu(url, data);
          } else {
            data.company_id = model.company_id;
            data.org_auth_id_list = this.ruleForm.org_list.map(x=>{
              return x.id;
            })
            data.role_id_list = this.ruleForm.role_id_list;
            data.user_name = model.user_name;
            data.user_pwd  = model.user_pwd;
            url = "sys/user/add"; 
            this.addUser(url, data);
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //新增保存
    addUser(url, data) {
      this.$api.post(url, data)
      .then(data => {
        if(data == '10001'){
          this.$message.error('无权操作该数据')
          this.$Bus.$emit('Loading',false);
          return
        }
        if(data){
          this.isShow = false
          this.$message({
            message: "新增成功",
            type: "success"
          });
          this.getUserList(this.company_id,this.keywords,this.pagination.currentPage,this.pagination.pageSize)
        }
        this.$Bus.$emit('Loading',false)
      })
    },
    //打开控制角色权限穿梭框
    openRole(){
      this.menuRoleisShow=true;
      this.ls_role_id_list=this.ruleForm.role_id_list;
      let url = '/sys/role/list?company_id=' + this.ruleForm.company_id + '&page_size=200'
      this.$api.get(url)
      .then(data =>{
        if(data == '10001'){
          this.$message.error('无权操作该数据')
          this.$Bus.$emit('Loading',false);
          return
        }
        // console.log(data);
        if(data){
          let _data = data.data
          if(_data.dataList && _data.dataList.length){
            for(let i in _data.dataList){
              _data.dataList[i].key = _data.dataList[i].id;
              _data.dataList[i].label = _data.dataList[i].role_name;
            }
            this.transferRoleData = _data.dataList
            this.showRoleTransfer = true
          }else{
            this.$message.warning('该企业控制角色为空')
          }
        }
      })
      .catch(err=>{
         console.log(err);
        this.$message.warning('该企业控制角色为空')
      })

    },
    //表格序号显示方法
    indexMethod(index){
      return index + ((this.pagination.currentPage - 1) * this.pagination.pageSize) + 1
    },
    //控制权限保存修改标签，将transferArr转换成string
    confirmRoleTransfer(){
      let list = this.transferRoleData;
      let val = this.ls_role_id_list;
      this.ruleForm.role_id_name = ''
      for(let i in list){
        for(let ii in val){
          if(val[ii] == list[i].id){
            if(this.ruleForm.role_id_name == ''){
              this.ruleForm.role_id_name += list[i].role_name
            }else{
              this.ruleForm.role_id_name += ',' + list[i].role_name
            }
          }
        }
      }
      this.ruleForm.role_id_list=val;
      this.showRoleTransfer = false;
    },
    //控制权限穿梭框change事件,存一个临时变量
    transferRoleChange(val){
      this.ls_role_id_list = val
    },
   
    //控制权限保存修改标签，将transferArr转换成string
    confirmOrgTransfer(){
      let val = this.submitOrgData;
      // this.ruleForm.role_id = val.join(',')
      this.ruleForm.org_auth_id_name = '';
        for(let item in val){
          if(this.ruleForm.org_auth_id_name == ''){
            this.ruleForm.org_auth_id_name += val[item].org_auth_name;
          }else{
            this.ruleForm.org_auth_id_name += ',' + val[item].org_auth_name;
          }
        }
      this.ruleForm.org_list=JSON.parse(JSON.stringify(val));
      this.showOrgTransfer = false;
    },
    //控制权限穿梭框change事件,存一个临时变量
    transferOrgChange(val){
      this.ruleForm.org_list = val
    },
    //每页显示条目个数change事件
    sizeChange(val){
      this.$Bus.$emit('Loading',true)
      this.getUserList(this.company_id,this.keywords,this.pagination.currentPage,val)
    },
    //分页change事件
    currentChange(val){
      this.$Bus.$emit('Loading',true)
      this.getUserList(this.company_id,this.keywords,val,this.pagination.pageSize)
    },
    userReset(data){
      // console.log(data);
      this.userId = data.id
      this.passwordReset = true;
    },
    //修改密码提交
    submitForm(formName){
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$Bus.$emit('Loading',true);
          let dataval={
            new_pwd:this.FormVal.newpwd
          };
          let mode={};
          mode.newPwd=dataval.new_pwd;   //  ?old_pwd='+dataval.old_pwd+'&new_pwd='+dataval.new_pwd
          mode.userId=this.userId;
          let url='/sys/user/reset-pwd';
          this.$api.post(url,mode)
          .then(data =>{
            if(data == '10001'){
              this.$message.error('无权操作该数据')
              this.$Bus.$emit('Loading',false);
              return
            }
            if(data)
            {
              this.$message({type: 'success',message: '重置成功'});
              this.passwordReset = false;
              this.$Bus.$emit('Loading',false);
            }
            else{
              this.$Bus.$emit('Loading',false);
            }
          }).catch(err=>{
            console.log(err,'重置密码错误');
            this.$Bus.$emit('Loading',false);
          });
        } else {
          return false;
        }
      });
    },
    //搜索用户
    usersearch(data){
      this.keywords = data;
      this.getUserList(this.company_id,data)
    },
    //重置修改密码表单
    reForm(formName){
      this.$refs.FormVal.resetFields();
      this.userId = ''
    },
    //点击详情
    userData(data){
      this.isDisabled = true
      this.isShow = true;
      this.$Bus.$emit('Loading',true)
      this.getUserData(data.id)
    },
    getUserData(id){
      let url = '/sys/user/get?user_id=' + id
      this.$api.get(url)
      .then(data=>{
        if(data == '10001'){
          this.$message.error('无权操作该数据')
          this.$Bus.$emit('Loading',false);
          return
        }
        if(data){
          let _data = data.data;
          this.ruleForm.company_id_arr = _data.company_nodel_location.split('-').filter( x =>{
            return x
          });
          // console.log(this.ruleForm.company_id_arr);
          this.ruleForm.company_id = _data.company_id
          this.ruleForm.id  = _data.id;
          this.ruleForm.user_name  = _data.user_name;
          let orgAuthVos = _data.orgAuthVos;
          if(orgAuthVos!=null)
          {
            this.ruleForm.org_auth_id_name = orgAuthVos.map(x=>{
              return x.org_auth_name
            }).join(',')
            this.ruleForm.org_list = orgAuthVos;
          }
          let roleVoList = _data.roleVoList;
          if(roleVoList)
          {
            this.ruleForm.role_id_name = roleVoList.map(x=>{
              return x.role_name
            }).join(',')
            this.ruleForm.role_id_list = roleVoList.map(x=>{
              return x.id;
            })
          }
        }
        this.$Bus.$emit('Loading',false)
      })
      .catch(err=>{
         console.log(err);
        this.$Bus.$emit('Loading',false)
      })
    },
    //修改保存
    modifyMenu(url,data){
      this.$api.post(url, data)
      .then(data => {
        if(data == '10001'){
          this.$message.error('无权操作该数据')
          this.$Bus.$emit('Loading',false);
          return
        }
        this.$Bus.$emit('Loading',false)
        if(data){
          this.isShow = false
          this.getUserList(this.company_id,this.keywords,this.pagination.currentPage,this.pagination.pageSize)
          this.$message({
            message: "修改成功",
            type: "success"
          });
        }
      })
      .catch(err=>{
         console.log(err);
        this.$Bus.$emit('Loading',false)
      })
    },
    //禁用接口
    disableUser(data,n){
      let msg = '';
      let isDisable = 0
      if(n){
        msg = "是否启用‘"+ data.user_name +"’？"
        isDisable = 0
      }else{
        msg = "是否禁用‘"+ data.user_name +"’？"
        isDisable = 1
      }
      this.$confirm(msg, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true
      })
      .then(() => {
        this.$Bus.$emit('Loading',true)
        let url = '/sys/user/disable-user-by-id?userId='+ data.id + '&isDisable='+ isDisable
        this.$api.post(url)
        .then(data=>{
          this.$Bus.$emit('Loading',true)
          if(data){
            this.getUserList(this.company_id,this.keywords,this.pagination.currentPage,this.pagination.pageSize)
            this.$message({
              message: "修改成功",
              type: "success"
            });
          }
        })
        .catch(()=>{
          this.$Bus.$emit('Loading',false)
        })
      })
      .catch(()=>{})
    },
    //删除用户
    userDel(data){
      this.$confirm("是否删除‘"+ data.user_name +"’？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true
      })
      .then(() => {
        this.$Bus.$emit('Loading',true)
        this.delData(data.id);
      })
      .catch(()=>{})
    },
    //删除接口
    delData(id) {
      let url = "/sys/user/del-user-by-id?userId=" + id
      this.$api.post(url)
      .then(data => {
        this.$Bus.$emit('Loading',true)
        if(data){
          this.getUserList(this.company_id,this.keywords,this.pagination.currentPage,this.pagination.pageSize)
          this.$message({
            message: "删除成功",
            type: "success"
          });
        }
      })
      .catch((err)=>{
         console.log(err);
        this.$Bus.$emit('Loading',false)
      })
    },
     //打开数据角色权限穿梭框
    openOrg(){
      let _this = this
      function recursive(arr,n) {
        for(let i in arr){
          if(arr[i].id == _this.ruleForm.company_id_arr[n]){
            //判断n等于company_id_arr长度-1时停止递归
            if(n === _this.ruleForm.company_id_arr.length - 1){
              _this.orgHeadText={
                name:_this.ruleForm.user_name,
                companyName:arr[i].company_name,
              }
            }else{
              recursive(arr[i].children,n+1)
            }
          }
        }
      }
      recursive(this.options,0)

      this.submitOrgData=[... new Set(this.ruleForm.org_list)];
      this.showOrgTransfer = true;
      this.getOrg_list(this.orgkeywords,this.orgPagination.currentPage,this.orgPagination.pageSize);
    },
    //获取待选数据权限表格数据
    getOrg_list(keywords = '',page = 1,page_size = 10){
      this.orgdxLoading=true;
      let url = '';
      if(this.isRoot){
        url = '/sys/org_auth/list?keywords='+keywords+'&page='+page+'&page_size='+page_size;
      }else{
        url = '/sys/org_auth/list?company_id=' + this.ruleForm.company_id + '&keywords=' + encodeURIComponent(keywords) + '&page='+page+'&page_size='+page_size;
      }
      this.$api.get(url)
      .then(data =>{
        this.orgData=[];
        if(data == '10001'){
          this.orgdxLoading=false;
          this.showOrgTransfer = false;
          this.$message.error('无权操作该数据');
          return
        }
        if(data){
          let _data = data.data;
          this.orgData = _data.dataList;
          this.orgPagination.total = _data.dataCount;
          this.orgPagination.currentPage = _data.pageCode;
          this.orgPagination.pageSize = _data.pageSize;
          this.tableCheckOrg=[];
          this.$nextTick(()=>{
            if (this.submitOrgData && this.submitOrgData.length > 0) {
              this.submitOrgData.forEach((ms,msIndex) => {
                for (let i = 0; i < this.orgData.length; i++) {
                  const el = this.orgData[i];
                  if(ms.id==el.id){
                    this.tableCheckOrg.push(el);
                    this.$refs.orgDataTable.toggleRowSelection(el, true);
                  }
                }
              })
            }   
          })
          this.orgdxLoading=false;
        }else{
          this.orgdxLoading=false;
          if(keywords)
          {
             this.$message.warning('不存在含有该关键字的的控制角色');
          }
          else{
            this.showOrgTransfer = false; 
            this.$message.warning('该企业控制角色为空');
          }
        }
      })
      .catch(err=>{
          this.orgdxLoading=false;
          if(keywords)
          {
             this.$message.warning('不存在含有该关键字的的控制角色');
          }
          else{
            this.showOrgTransfer = false; 
            this.$message.warning('该企业控制角色为空');
          }
           console.log(err);
      })
    },
    //org 数据权限搜索
    orgSearch(data){
      this.orgkeywords=data;
      this.getOrg_list(this.orgkeywords,'1',this.orgPagination.pageSize);
    },
    //分页change事件
    orgCurrentChange(val){
      this.getOrg_list(this.orgkeywords,val,this.orgPagination.pageSize);
    },
    //每页显示条目个数change事件
    orgSizeChange(val){
      this.getOrg_list(this.orgkeywords,'1',val);
    },
    //已选删除
    delOrg(val){
      this.orgData.forEach((em)=>{
          if(em.id==val.id){
            this.$refs.orgDataTable .toggleRowSelection(em,false);
          }
      });
      this.tableCheckOrg=this.tableCheckOrg.filter(item=> item.id!=val.id);
      this.submitOrgData=this.submitOrgData.filter(item=> item.id!=val.id);
    },
    //点击复选框
    checkOrgRow(list,row){
      //选中
      if(list.length>this.tableCheckOrg.length){ 
        this.submitOrgData.push(row);
      }
      else{ //取消选择
        for(let i=0;i<this.submitOrgData.length;i++)
        {
          if(this.submitOrgData[i].id==row.id){
            this.submitOrgData.splice(i,1);
          }
        }
      }
      this.tableCheckOrg=JSON.parse(JSON.stringify(list));
    },
    //数据权限复选框全选
    checkoRgAll(list){
      // let arr= [...new Set([...this.ruleForm.org_list,...list])];
      if(list.length)
      {
        let arrIds=this.submitOrgData.map(item=>item.id);
        let newArr=list.filter(item=>!arrIds.includes(item.id));
        this.submitOrgData=[...this.submitOrgData,...newArr];
        this.tableCheckOrg=JSON.parse(JSON.stringify(this.orgData));
      }
      else{
        let qxarrIds=this.orgData.map(item=>item.id);
        this.submitOrgData=this.submitOrgData.filter(item=>!qxarrIds.includes(item.id));
        this.tableCheckOrg=[];
      }
      
    },
    //数据权限弹框关闭
    orgClose(){
      this.orgkeywords='';
      this.orgHeadText={
        name:'',
        companyName:'',
      }
    },
    //菜单弹框关闭
    menuClose(){
      this.menuRoleisShow=false;
    }
  }
};


</script>
